<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>收入来源统计</title>
    <#include "/header.html">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <script src="${request.contextPath}/statics/plugins/layui/layui.all.js"></script>
    <link rel="stylesheet" href="${request.contextPath}/statics/css/chartStyle.css">
    <script src="${request.contextPath}/statics/js/echarts.min.js"></script>
    <script src="${request.contextPath}/statics/js/transData.js"></script>
</head>
<style>
    .bootstrap-select{
        width: 100% !important;
    }
    .glyphicon-arrow-up{
        color: red;
    }

    .glyphicon-arrow-down{
        color: #76d471;
    }
    #tableData{
        margin: 20px 0;
    }
    #tableData tr td,th{
        text-align: center;
        white-space: nowrap;
    }

</style>
<body>
<div id="index">
    <div class="layui-container" style="width: 100%;">
        <div class="layui-row" style="margin-top: 10px;">
            <div class="layui-col-md2 ">
                <select class="selectpicker" id="platformId" data-actions-box="true" data-select-all-text="全选" data-deselect-all-text="取消全选" multiple title="请选择平台名称"   style="width:100%;" >

                </select>
            </div>
            <div class="layui-col-md1 " style="padding-left: 20px;width: 140px;">
                <div class="btn-group" role="group" id="timetype">
                    <div class="btn btn-default active" id="timetype1" data-id="1">日</div>
                    <div class="btn btn-default" id="timetype2" data-id="2">周</div>
                    <div class="btn btn-default" id="timetype3" data-id="3">月</div>
                </div>
            </div>
            <div class="layui-col-md2" style="padding-left: 20px;">
                <input type="text" class="form-control" required  id="TimeDate"  placeholder="请输入查询日期"  autocomplete="off" >
                <input type="text" class="form-control" required style="display: none"  id="TimeYear"  placeholder="请选择年份"  autocomplete="off" >
                <input type="text" class="form-control" required style="display: none" id="TimeMonth"  placeholder="请输入查询月份"  autocomplete="off" >
            </div>
            <div class="layui-col-md1 weeks" style="padding-left: 20px;" >
                <select class="selectpicker"   data-live-search="true"  id="weeks" title="请选择周"   style="width:100%">

                </select>
            </div>
            <div class="layui-col-md2" style="padding-left: 20px;">
                <select class="selectpicker" data-actions-box="true" data-select-all-text="全选" data-deselect-all-text="取消全选" data-deselect-all-text="全选" id="siteSelect" title="请选择字段" multiple  style="width:100%;"></select>
            </div>
            <div class="layui-col-md3 " style="padding-left: 20px;">
                <div class="btn btn-default" id="search" onclick="reload()">查询</div>
                <#if shiro.hasPermission("data:dataQuery:export")>
                <div class="btn btn-default" id="export">导出</div>
            </#if>
        </div>
    </div>
</div>
<div class="col-sm-12 select-info table-striped" style="overflow: auto;">
    <!--<table id="bootstrap-table" data-mobile-responsive="true"></table>-->
    <table class="table table-bordered table-hover" id="tableData" >
        <!--<tr>-->
        <!--<th>类型[item]</th>-->
        <!--<th>有银子</th>-->
        <!--<th>趣转发</th>-->
        <!--</tr>-->
        <!--<tr>-->
        <!--<td>转发人数[param]</td>-->
        <!--<td>1[value]</td>-->
        <!--<td>2</td>-->
        <!--</tr>-->
        <!--<tr>-->
        <!--<td>转发人数[param]</td>-->
        <!--<td>1[value]</td>-->
        <!--<td>2</td>-->
        <!--</tr>-->
    </table>
    <!--<table class="table table-bordered table-hover">-->
    <!--<tr>-->
    <!--<th>类型</th>-->
    <!--<th>有银子</th>-->
    <!--<th>趣转发</th>-->
    <!--</tr>-->
    <!--<tr>-->
    <!--<td>-->
    <!--转发人数-->
    <!--</td>-->
    <!--<td>-->
    <!--<div>-->
    <!--<span>对比前</span>-->
    <!--<span>1</span>-->
    <!--</div>-->
    <!--<div>-->
    <!--<span>对比后</span>-->
    <!--<span>1</span>-->
    <!--</div>-->
    <!--<div>-->
    <!--<span>上升幅度</span>-->
    <!--<span>1%</span>-->
    <!--</div>-->
    <!--</td>-->
    <!--<td>-->
    <!--<div>-->
    <!--<span>对比前</span>-->
    <!--<span>1</span>-->
    <!--</div>-->
    <!--<div>-->
    <!--<span>对比后</span>-->
    <!--<span>1</span>-->
    <!--</div>-->
    <!--<div>-->
    <!--<span>上升幅度</span>-->
    <!--<span>1%</span>-->
    <!--</div>-->
    <!--</td>-->
    <!--</tr>-->

    <!--</table>-->
</div>

<script>
    var laydate = layui.laydate;

    laydate.render({
        elem: '#TimeDate',
        range: true,
        position: 'fixed',
        change:function(value, date, endDate){

        }
    });
    laydate.render({
        elem: '#TimeYear',
        type: 'year',
        value: new Date(),
        position: 'fixed',
        done:function(value, date, endDate){
            getWeek(value)
        }
    });
    laydate.render({
        elem: '#TimeMonth',
        type: 'month',
        value: new Date(),
        position: 'fixed',
        done:function(value, date, endDate){
            console.log(value, date, endDate,'3333333333333')
        }
    });
    function gettime(num){
        var _thisdate =new Date() - (1000*60 *60 *24*num)
        var date = new Date(_thisdate);
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
    }
    //初始化默认时间
    var startTimes ='';
    var endTimes='';
    $('#TimeDate').val(gettime(1)+' - '+gettime(1));
    startTimes = gettime(1);
    endTimes = gettime(1);
    //
    var now = new Date();
    var year = now.getFullYear();
    getWeek(year)
    $('.weeks').hide()
    var timeIndex = 0;
    $('#timetype .btn').each(function(index){
        $(this).click(function(){
            $('.form-control').hide()
            $('.weeks').hide()
            timeIndex = index;
            if(index==0){
                $('#TimeDate').show();
            }else if(index==1){
                $('.weeks').show()
                $('#TimeYear').show();
            }else if(index==2){
                $('#TimeMonth').show();
            }
            $('#timetype .btn').removeClass('active');
            $(this).addClass('active');
            reload()
        })
    });
    $('#export').click(function(){
        // var data={
        //     "startDate":startTimes,
        //     "endDate":endTimes,
        //     "params":$('#siteSelect').val(),
        //     "platformId":$('#platformId').val()?$('#platformId').val():null
        // }
        var data = setParams();

        //console.log(baseURL +"incomeStatis/downloadPlatformIncomeContrast?startDate="+data.startDate+"&endDate="+data.endDate+"&params="+data.params+"&platformId="+data.platformId)
        window.location.href=baseURL +"incomeStatis/downloadPlatformIncomeContrast?startDate="+data.startDate+"&endDate="+data.endDate+"&params="+data.params+"&platformId="+data.platformId

    })
    function setParams() {
        if(timeIndex==0){
            if(!$('#TimeDate').val()){
                layer.msg('时间格式不对')
                return;
            }
            startTimes = $('#TimeDate').val().split(' - ')[0]?$('#TimeDate').val().split(' - ')[0]:'';
            endTimes = $('#TimeDate').val().split(' - ')[1]?$('#TimeDate').val().split(' - ')[1]:'';
        }else if(timeIndex==1){
            if(!$('#TimeYear').val() || !$('#weeks').val()){
                layer.msg('时间格式不对')
                return;
            }
            startTimes = $('#weeks').val().split(' - ')[0]?$('#weeks').val().split(' - ')[0]:'';
            endTimes = $('#weeks').val().split(' - ')[1]?$('#weeks').val().split(' - ')[1]:'';
        }else if(timeIndex==2){
            if(!$('#TimeMonth').val()){
                layer.msg('时间格式不对')
                return;
            }
            startTimes = $('#TimeMonth').val() + '-01';
            endTimes =$('#TimeMonth').val()+'-'+new Date($('#TimeMonth').val().split('-')[0],$('#TimeMonth').val().split('-')[1],0).getDate()
        }
       // console.log(startTimes,endTimes,'sssssssssssss')

        // indexloading = layer.load(2);
        var params = {
            startDate:startTimes,
            endDate:endTimes,
            params:$('#siteSelect').val(),
            platformId:$('#platformId').val()?transIntData($('#platformId').val()):null
        };
        var minData;
        var maxData;
        if(params.startDate>params.endDate){
            maxData = params.startDate;
            minData = params.endDate;
            params.endDate = maxData;
            params.startDate = minData;
        }
        return params;
    }

    function reload() {
        var params =  setParams();
        $("#search").attr("disabled",'disabled');
        var  indexLoading = layer.load(2);
        $.ajax({
            type : "POST",
            url : baseURL + 'incomeStatis/findPlatformIncomeContrast',
            contentType : "application/json",
            data : JSON.stringify(params),
            dataType:'json',
            success : function(r) {
                $("#search").attr("disabled",false);
                if (r.code === 0) {
                    showTable(r.result);
                    layer.close(indexLoading);
                } else {
                    alert(r.msg);
                }
            }
        });
    }
    function showTable(data) {
             var theadH = '<thead><tr><th>平台名称</th><th>日期</th>';
             var tbodayH = '<tbody>';
             for(var i=0;i<data.length;i++){
                   for(var j=0;j<data[0].statisData[0].length;j++){
                       if(i == 0 ){
                           if(data[0].statisData[0][j].paramDesc){
                               theadH = theadH + '<th><strong data-toggle="tooltip" data-placement="top" title="'+data[0].statisData[0][j].paramDesc+'">'+data[0].statisData[0][j].param+'</strong></th>';
                           }else{
                               theadH = theadH + '<th>'+data[0].statisData[0][j].param+'</th>';
                           }

                        }
                    }
                   for(var k=0;k<data[i].statisData.length;k++){

                        k == 0 ? tbodayH = tbodayH + '<tr><td rowspan="'+data[i].statisData.length+'">'+data[i].platformNickName+'</td>' : tbodayH = tbodayH + '<tr>';
                         for(var m=0;m<data[i].statisData[k].length;m++){
                             if(m == 0){
                                 tbodayH = tbodayH + '<td>'+data[i].statisData[k][m].startDate+'</td>';
                             }
                             tbodayH = tbodayH +  '<td>'+data[i].statisData[k][m].value+'<br />'+data[i].statisData[k][m].rateValue+'</td>';
                         }
                       tbodayH = tbodayH + '</tr>';
                   }
             }
            theadH = theadH + '</tr></thead>';
            tbodayH = tbodayH + '</tbody>';
            var str = theadH +　tbodayH;
            //console.log(str);
           $("#tableData").html(str);
           $('[data-toggle="tooltip"]').tooltip();
        // console.log(data);
        // var platformName = [];
        // var dataType = [];
        // var allData = [];
        // var resData = [];
        // for(var item in data){
        //     platformName.push(item);
        //     for(var i=0;i<data[item].length;i++){
        //         allData.push(data[item][i]);
        //         if(dataType.indexOf(data[item][i].param)<0){
        //             dataType.push(data[item][i].param);
        //         }
        //     }
        // }
        // //console.log(dataType);
        // //console.log(allData)
        // for(var k=0;k<dataType.length;k++){
        //     var dataValue = [];
        //     var dataItem = {
        //         dataTypeName:allData[k],
        //         dataItemValue:dataValue
        //     };
        //     for(var j=0;j<allData.length;j++){
        //         if(allData[j].param == dataType[k]){
        //             dataValue.push({value:allData[j].value,rateValue:allData[j].rateValue});
        //         }
        //     }
        //     resData.push(dataItem);
        // }
        // //console.log(resData);
        // var str = '<thead><tr><th>类型</th>';
        // for(item2 in data){
        //     str = str + '<th>'+item2+'</th>';
        // }
        // str = str + '</tr></thead><tbody>';
        // for(var s=0;s<resData.length;s++){
        //     str = str + '<tr><td>'+resData[s].dataTypeName.param+'</td>';
        //     for(var z=0;z<resData[s].dataItemValue.length;z++){
        //         str = str + '<td>'+resData[s].dataItemValue[z].value+'<br>'+resData[s].dataItemValue[z].rateValue+'</td>';
        //     }
        //     str = str + '</tr>';
        // }
        // str = str + '</tbody>';
        // //console.log(str);
        // $("#tableData").html(str);
    }
    function getWeek(years) {
        function formatDig(num) {
            return num > 9 ? '' + num : '0' + num;
        }
        function add0(m) {
            return m < 10 ? '0' + m : m
        }
        function formatDate(mill) {
            var time = new Date(mill);
            var y = time.getFullYear();
            var m = time.getMonth() + 1;
            var d = time.getDate();
            return y + '-' + add0(m) + '-' + add0(d);
        }
        function* createWeeks(year) {
            const ONE_DAY = 24 * 3600 * 1000;
            let start = new Date(year, 0, 1),
                end = new Date(year, 11, 31);
            let firstDay = start.getDay() || 7,
                lastDay = end.getDay() || 7;
            let startTime = +start,
                endTime = startTime + (7 - firstDay) * ONE_DAY,
                _endTime = end - (7 - lastDay) * ONE_DAY;
            yield [startTime, endTime];
            startTime = endTime + ONE_DAY;
            endTime = endTime + 7 * ONE_DAY;
            while (endTime < _endTime) {
                yield [startTime, endTime];
                startTime = endTime + ONE_DAY;
                endTime = endTime + 7 * ONE_DAY;
            }
            yield [startTime, +end];
        }
        let index = 1;
        var obj = {}
        var _html ="";
        var _index ='';
        for (let i of createWeeks(years)) {
            let start = i[0],
                end = i[1];
            if(formatDig(getWeekOfYear())==formatDig(index)){
                _index =formatDate(start)+' - '+formatDate(end);
            }
            _html = _html + '<option value="'+formatDate(start)+' - '+formatDate(end)+'">第' + (formatDig(index++)) + '周</option>'

        }
        $('#weeks').html(_html);
        $('#weeks').selectpicker('val',_index?_index:'');
        $('#weeks').selectpicker('refresh');
    }
    function transIntData(arr) {
        // console.log(arr);
        var newArr = [];
        arr.map(function (item) {
            newArr.push(parseInt(item));
        });
        return newArr;
    }
    function getWeekOfYear(){
        var today = new Date();
        var firstDay = new Date(today.getFullYear(),0, 1);
        var dayOfWeek = firstDay.getDay();
        var spendDay= 1;
        if (dayOfWeek !=0) {
            spendDay=7-dayOfWeek+1;
        }
        firstDay = new Date(today.getFullYear(),0, 1+spendDay);
        var d =Math.ceil((today.valueOf()- firstDay.valueOf())/ 86400000);
        var result =Math.ceil(d/7);
        return result+1;
    };
    $.ajax({
        type : "get",
        url : baseURL+"platform/findAllPlatform",
        dataType : "json",
        success: function(data) {
            if(data.code==0){
                var _html = ''
                for(var i=0;i<data.platformList.length;i++){
                    _html = _html + '<option value="'+data.platformList[i].platformId+'">'+data.platformList[i].nickName+'</option>'
                }
                $('#platformId').append(_html);
                $('#platformId').val(data.platformList[0].platformId);
                $('#platformId').selectpicker('refresh');
                var paramType = 0;
                if(isAuth('data:dataQuery:common') && !isAuth('data:dataQuery:business')){
                    paramType = 1;
                }else if(!isAuth('data:dataQuery:common') && isAuth('data:dataQuery:business')){
                    paramType=2
                }
                $.ajax({
                    type : "post",
                    url : baseURL+"incomeStatis/getPlatformIncomeContrastParam",
                    data:JSON.stringify({
                        'paramType':paramType
                    }),
                    contentType : "application/json",
                    dataType : "json",
                    success: function(data) {
                        if(data.code==0){
                            var _html = '';
                            var selectedVal = [];
                            for(var i=0;i<data.result.length;i++){
                                _html = _html + '<option value="'+data.result[i].dateKey+'">'+data.result[i].dataName+'</option>';
                                selectedVal.push(data.result[i].dateKey);
                            }
                            $('#siteSelect').append(_html);
                            $('#siteSelect').val(selectedVal);
                            $('#siteSelect').selectpicker('refresh');
                            var params = {
                                startDate:startTimes,
                                endDate:endTimes,
                                params:$('#siteSelect').val(),
                                platformId:$('#platformId').val()?transIntData($('#platformId').val()):null
                            };
                            var  indexLoading = layer.load(2);
                            $.ajax({
                                type : "POST",
                                url : baseURL + 'incomeStatis/findPlatformIncomeContrast',
                                contentType : "application/json",
                                data : JSON.stringify(params),
                                dataType:'json',
                                success : function(r) {
                                    if (r.code === 0) {
                                        showTable(r.result);
                                        layer.close(indexLoading);
                                    } else {
                                        alert(r.msg);
                                    }
                                }
                            });
                            // $('#bootstrap-table')
                            //     .bootstrapTable(
                            //         {
                            //             method : 'post', // 服务器数据的请求方式 get or post
                            //             url : baseURL + 'platformStatis/findPlatformContrast', // 服务器数据的加载地址
                            //             showRefresh : true,
                            //             showToggle : true,
                            //             showColumns : true,
                            //             showExport :true,
                            //             exportOptions:{
                            //                 ignoreColumn: [],
                            //             },
                            //             sortable: true,
                            //             sortName:"dateStr",// 排序列名称
                            //             sortOrder: "desc",
                            //             iconSize : 'outline',
                            //             toolbar : '#exampleToolbar',
                            //             striped : true, // 设置为true会有隔行变色效果
                            //             dataType : "json", // 服务器返回的数据类型
                            //             pagination : false, // 设置为true会在底部显示分页条
                            //             // queryParamsType : "limit",
                            //             // //设置为limit则会发送符合RESTFull格式的参数
                            //             singleSelect : false, // 设置为true将禁止多选
                            //             // contentType : "application/x-www-form-urlencoded",
                            //             // //发送到服务器的数据编码类型
                            //             pageSize : 999, // 如果设置了分页，每页数据条数
                            //             pageNumber : 1, // 如果设置了分布，首页页码
                            //             // search : true, // 是否显示搜索框
                            //             //showColumns : false, // 是否显示内容下拉框（选择显示的列）
                            //             sidePagination : "server", // 设置在哪里进行分页，可选值为"client" 或者
                            //             // "server"
                            //             queryParams : function(params) {
                            //                 return {
                            //                     // 说明：传入后台的参数包括offset开始索引，limit步长，sort排序列，order：desc或者,以及所有列的键值对
                            //                     "startDate":startTimes,
                            //                     "endDate":endTimes,
                            //                     "params":$('#siteSelect').val(),
                            //                     "platformId":$('#platformId').val()?$('#platformId').val():null
                            //                 };
                            //             },
                            //             onLoadSuccess:function(data){
                            //                 $("#search").attr("disabled",false);
                            //                 layer.close(indexloading);
                            //             },
                            //             onLoadError:function(){
                            //                 $("#search").attr("disabled",false);
                            //                 layer.close(indexloading);
                            //             },
                            //             // //请求服务器数据时，你可以通过重写参数的方式添加一些额外的参数，例如 toolbar 中的参数 如果
                            //             // queryParamsType = 'limit' ,返回参数必须包含
                            //             // limit, offset, search, sort, order 否则, 需要包含:
                            //             // pageSize, pageNumber, searchText, sortName,
                            //             // sortOrder.
                            //             // 返回false将会终止请求
                            //             columns : [
                            //
                            //                 {
                            //                     field : 'param',
                            //                     align:'center',
                            //                     title : '类型名称'
                            //                 },
                            //
                            //                 {
                            //                     field : 'value',
                            //                     align:'center',
                            //                     title : '总数'
                            //                 }]
                            //         });
                        }else{
                            layer.msg('数据获取失败');
                        }
                    },
                    error:function(){

                        layer.msg('数据获取失败');
                    }
                });
            }else{
                layer.msg('数据获取失败');
            }
        },
        error:function(){

            layer.msg('数据获取失败');
        }
    });

</script>

</body>

</html>